<template>
  <div class="page-container">
    <div class="navigation-container">
      <div class="top-row-layout">
        <el-card class="control-card">
          <template #header>
            <div class="card-header">
              <span>路线导航</span>
            </div>
          </template>
          <div class="amap-style-control-panel">
            <div class="input-wrapper">
              <el-autocomplete
                v-model="startPoint"
                :fetch-suggestions="querySearchStart"
                placeholder="输入或在地图上选择起点"
                @select="handleSelectStart"
                class="route-input start-input"
                clearable
              >
                <template #prefix>
                  <el-icon :size="20" color="#34D399"><Flag /></el-icon>
                </template>
              </el-autocomplete>

              <el-autocomplete
                v-model="endPoint"
                :fetch-suggestions="querySearchEnd"
                placeholder="输入或在地图上选择终点"
                @select="handleSelectEnd"
                class="route-input end-input"
                clearable
              >
                <template #prefix>
                  <el-icon :size="20" color="#F87171"><Location /></el-icon>
                </template>
              </el-autocomplete>

              <div class="swap-button-container">
                <el-button @click="swapPoints" :icon="Switch" circle title="交换起点和终点" />
              </div>
            </div>

            <div class="search-button-wrapper">
              <el-button
                type="primary"
                @click="searchRoute"
                :loading="loading"
                :disabled="!isMapReady"
                class="search-button"
              >
                查 询
              </el-button>
            </div>
          </div>
        </el-card>

        <el-card class="info-card">
           <div class="update-info">
            <el-icon :size="20" class="refresh-icon"><Refresh /></el-icon>
            <span>同步高德地图实时更新</span>
          </div>
        </el-card>
      </div>

      <div
        class="map-layout-container"
        v-loading="!isMapReady"
        element-loading-text="地图资源加载中..."
        element-loading-background="rgba(255, 255, 255, 0.8)"
      >
        <div id="map-container" class="map-container"></div>
        <el-card id="panel-card" class="panel-card" shadow="never">
          <div id="panel" class="route-panel"></div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { ElMessage } from 'element-plus';
import { Flag, Location, Switch, Refresh } from '@element-plus/icons-vue';
import AMapLoader from '@amap/amap-jsapi-loader';

// --- 配置项 ---
const A_MAP_KEY = 'bda5c73a52835b24226f8087049b5d7e';
const A_MAP_SECURITY_KEY = '88435cadb2fc710dbc93abc1e3d63064';

// --- 响应式状态 ---
const startPoint = ref('中南大学新校区');
const endPoint = ref('五一广场');
const loading = ref(false);
const isMapReady = ref(false);

// --- 地图与插件实例 ---
let map = null;
let driving = null;
let autoCompleteStart = null;
let autoCompleteEnd = null;

// --- 功能函数 ---
const swapPoints = () => {
  [startPoint.value, endPoint.value] = [endPoint.value, startPoint.value];
};

const initMap = () => {
  window._AMapSecurityConfig = {
    securityJsCode: A_MAP_SECURITY_KEY,
  };

  AMapLoader.load({
    key: A_MAP_KEY,
    version: '2.0',
    plugins: ['AMap.Driving', 'AMap.AutoComplete'],
  })
    .then((AMap) => {
      map = new AMap.Map('map-container', {
        zoom: 12,
        center: [112.938888, 28.115082],
        resizeEnable: true,
      });

      driving = new AMap.Driving({
        map: map,
        panel: 'panel',
        policy: AMap.DrivingPolicy.LEAST_TIME,
      });

      const autoCompleteOptions = {
        city: '全国',
      };
      autoCompleteStart = new AMap.AutoComplete(autoCompleteOptions);
      autoCompleteEnd = new AMap.AutoComplete(autoCompleteOptions);

      ElMessage.success('地图及插件加载成功');
      isMapReady.value = true;
    })
    .catch((e) => {
      console.error(e);
      ElMessage.error('地图加载失败，请检查Key和网络');
    });
};

const querySearchAsync = (queryString, cb, autoCompleteInstance) => {
  if (!autoCompleteInstance || !queryString) {
    cb([]);
    return;
  }
  autoCompleteInstance.search(queryString, (status, result) => {
    if (status === 'complete' && result.tips) {
      const suggestions = result.tips.map((tip) => ({
        value: (tip.district || '') + (tip.name || ''),
        address: tip.address || '详情未知',
      }));
      cb(suggestions);
    } else {
      cb([]);
    }
  });
};

const querySearchStart = (queryString, cb) => {
  querySearchAsync(queryString, cb, autoCompleteStart);
};
const querySearchEnd = (queryString, cb) => {
  querySearchAsync(queryString, cb, autoCompleteEnd);
};

const handleSelectStart = (item) => {
  startPoint.value = item.value;
};
const handleSelectEnd = (item) => {
  endPoint.value = item.value;
};

const searchRoute = () => {
  if (!driving) {
    ElMessage.error('地图尚未初始化完成，请稍候');
    return;
  }
  if (!startPoint.value || !endPoint.value) {
    ElMessage.warning('起点和终点不能为空！');
    return;
  }
  loading.value = true;
  driving.search(
    [{ keyword: startPoint.value }, { keyword: endPoint.value }],
    (status, result) => {
      loading.value = false;
      if (status === 'complete') {
        ElMessage.success('路线规划成功');
      } else {
        ElMessage.error('路线规划失败: ' + (result.info || '未知错误'));
        driving.clear();
      }
    }
  );
};

// --- 生命周期钩子 ---
onMounted(initMap);
onUnmounted(() => {
  if (map) {
    map.destroy();
  }
});
</script>

<style scoped>
/* 全局页面容器，用于约束宽度和居中 */
.page-container {
  display: flex;
  justify-content: center;
  padding: 20px;
  box-sizing: border-box;
}

.navigation-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
  width: 100%;
  /* MODIFIED: Increased max-width to widen the left column */
  max-width: 1350px;
}

/* 上方卡片行布局 */
.top-row-layout {
  display: flex;
  gap: 20px;
  width: 100%;
}

/* 控制卡片，宽度由flex-grow决定 */
.control-card {
  flex-grow: 1;
  min-width: 0;
  border-radius: 12px !important;
}

/* 信息提示卡片 */
.info-card {
  width: 380px;
  flex-shrink: 0;
  border-radius: 12px !important;
  display: flex;
  align-items: center;
  justify-content: center;
}

:deep(.info-card .el-card__body) {
  display: flex;
  align-items: center;
  height: 100%;
}

/* MODIFIED: Increased font-size and weight */
.update-info {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: 500;
  color: #606266; /* Slightly darker text for better readability */
  white-space: nowrap;
}

.refresh-icon {
  margin-right: 8px; /* Increased margin */
  color: var(--el-color-primary);
}


/* --- 左侧控制面板内部样式 (无改动) --- */
.amap-style-control-panel {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.input-wrapper {
  position: relative;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.route-input {
  width: 100%;
  --el-input-height: 48px;
}

.route-input.start-input {
  --el-input-bg-color: #f0fdf4;
  --el-input-border-color: #d1fae5;
}
.route-input.end-input {
  --el-input-bg-color: #fff1f2;
  --el-input-border-color: #ffe4e6;
}
.route-input:deep(.el-input__wrapper) {
  border-radius: 8px;
  box-shadow: none !important;
  border: 1px solid var(--el-input-border-color);
}
.route-input:deep(.el-input__wrapper.is-focus) {
  border-color: var(--el-color-primary) !important;
}

:deep(.route-input .el-input__prefix) {
  display: flex;
  align-items: center;
  margin-right: 8px;
  margin-left: 5px;
}

.swap-button-container {
  position: absolute;
  top: 50%;
  right: 15px;
  transform: translateY(-50%);
  z-index: 10;
}
:deep(.swap-button-container .el-button) {
  --el-button-size: 32px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.search-button-wrapper {
  display: flex;
  justify-content: flex-end;
}

.search-button {
  width: auto;
  min-width: 130px;
  height: 48px;
  font-size: 16px;
  letter-spacing: 2px;
  border-radius: 8px;
}


/* --- 地图和结果面板布局 (无改动) --- */
.map-layout-container {
  display: flex;
  gap: 20px;
  width: 100%;
  height: 600px;
  flex-grow: 1;
}

.map-container {
  flex-grow: 1;
  height: 100%;
  border-radius: 12px;
  border: 1px solid #dcdfe6;
  min-width: 0;
}

.panel-card {
  width: 380px;
  height: 100%;
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
  border-radius: 12px !important;
}

:deep(.panel-card .el-card__body) {
  padding: 0;
  height: 100%;
  flex-grow: 1;
  overflow: hidden;
}

.route-panel {
  width: 100%;
  height: 100%;
  overflow-y: auto;
  box-sizing: border-box;
}
.route-panel::-webkit-scrollbar { width: 6px; }
.route-panel::-webkit-scrollbar-thumb { background: #dcdfe6; border-radius: 3px; }
.route-panel::-webkit-scrollbar-thumb:hover { background: #c0c4cc; }


/* --- 高德地图结果面板美化 (无改动) --- */
:deep(.route-panel .amap-call) { display: none; }
:deep(.route-panel .amap-lib-driving) { border: none; overflow: hidden; padding: 10px 20px; }
:deep(.amap-lib-driving-route-title) { display: flex; flex-direction: column; padding: 15px; margin-bottom: 20px; background-color: var(--el-color-primary-light-9) !important; border: 1px solid var(--el-color-primary-light-8) !important; border-radius: 8px; }
:deep(.amap-lib-driving-route-title .amap-lib-driving-route-text) { font-size: 16px; font-weight: 600; color: #303133; }
:deep(.amap-lib-driving-route-title .amap-lib-driving-route-description) { font-size: 14px; color: var(--el-color-primary); font-weight: 500; margin-top: 5px; }
:deep(.amap-lib-driving-bus-route-title:hover) { background-color: var(--el-color-primary-light-9) !important; }
:deep(.amap-lib-driving-point) { margin-bottom: 10px; }
:deep(.amap-lib-driving-point .amap-lib-driving-point-icon) { width: 12px !important; height: 12px !important; }
:deep(.amap-lib-driving-point-start .amap-lib-driving-point-icon) { background-color: #34d399 !important; box-shadow: 0 0 5px #34d399; }
:deep(.amap-lib-driving-point-end .amap-lib-driving-point-icon) { background-color: #f87171 !important; box-shadow: 0 0 5px #f87171; }
:deep(.amap-lib-driving-point .amap-lib-driving-point-content) { font-size: 15px; font-weight: 600; color: #303133; }
:deep(.amap-lib-driving-line) { padding: 15px 0; border-bottom: 1px dashed #e4e7ed; display: flex; align-items: center; }
:deep(.amap-lib-driving-line:last-child) { border-bottom: none; }
:deep(.amap-lib-driving-step-icon) { background-color: #f0f2f5 !important; border: 1px solid #e4e7ed; box-shadow: none !important; border-radius: 50% !important; color: #606266; font-size: 18px !important; line-height: 28px !important; width: 28px !important; height: 28px !important; margin-right: 15px; }
:deep(.amap-lib-driving-step-info) { color: #303133; line-height: 1.6; }
:deep(.amap-lib-driving-step-distance) { color: #909399; }
</style>